package com.kinglone.back.blog.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.kinglone.back.blog.model.Blog;
import com.kinglone.back.blog.service.BlogService;
import com.kinglone.common.entity.DateJsonValueProcessor;
import com.kinglone.common.entity.PageBean;
import com.kinglone.common.lucene.BlogIndex;
import com.kinglone.common.utils.DateUtils;
import com.kinglone.common.utils.JSONMessageView;
import com.kinglone.common.utils.PropertieUtil;
import com.kinglone.common.utils.ResponseUtil;
import com.kinglone.common.utils.StringUtil;


@Controller
@RequestMapping("/back/blog")
public class BlogController {

	@Autowired
	private BlogService blogService;
	
	// 博客索引
	private BlogIndex blogIndex=new BlogIndex();
	
	/**
	 * 分页查询博客数据
	 * @param page
	 * @param rows
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/list")
	public String list(@RequestParam(value = "page", required = false) String page,@RequestParam(value = "rows", required = false) String rows,
			Blog s_blog,HttpServletResponse response) throws Exception{
		
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", StringUtil.formatLike(s_blog.getTitle()));
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		
		List<Blog> blogList = blogService.list(map);
		Long total = blogService.getTotal(map);
		
		JsonConfig jsonConfig=new JsonConfig();
		jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(blogList,jsonConfig);
		JSONObject result = new JSONObject();
		
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 保存博客
	 * @param blog
	 * @param response
	 * @return
	 */
	@RequestMapping("/save")
	public String save(Blog blog,HttpServletResponse response)throws Exception{
		
		int resultTotal =0;//操作的记录数
		if(blog.getId()==null){
			resultTotal = blogService.add(blog);
			blogIndex.addIndex(blog);//添加博客索引
		}else{
			resultTotal = blogService.update(blog);
			blogIndex.updateIndex(blog); // 更新博客索引
		}	
		JSONObject result = new JSONObject();
		if(resultTotal > 0){
			result.put("success", true);
		}else{
			result.put("success", false);
		}
		
		ResponseUtil.write(response, result);
		return null;	
	}
	
	/**
	 * 根据id查询博客
	 * @param id
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findBlogById")
	public String findBlogById(@RequestParam(value="id")String id,HttpServletResponse response)throws Exception{
		
		Blog blog = blogService.findBlogById(Integer.valueOf(id));
		JSONObject result = JSONObject.fromObject(blog);
		ResponseUtil.write(response, result);
		return null;	
	}
	
	/**
	 * 根据id删除博客
	 * @param ids
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public String delete(@RequestParam(value="ids")String ids,HttpServletResponse response)throws Exception{
		String[] strIds = ids.split(",");
		for(int i=0;i<strIds.length;i++){
			blogService.delete(Integer.valueOf(strIds[i]));
			blogIndex.deleteIndex(strIds[i]); // 删除对应博客的索引
		}
		JSONObject result = new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}
	
	/**
	 * 上传图片
	 */
	@RequestMapping("/saveImage")
	public JSONMessageView saveImage(HttpServletRequest request,@RequestParam("thumbnail") MultipartFile thumbnail){
		
		JSONMessageView msg = new JSONMessageView(-1,"上传失败!",null);
		try {		
			//上传路径
			String basepath = PropertieUtil.getValue("config.properties", "upload_url");
			//相对保存路径
			String relativePath="/upload/img/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
			String holePath=basepath+relativePath;
			System.out.println("完整存储路径："+holePath);
			File f=new File(holePath);
			if(!f.exists()){
				f.mkdirs();
			}
			//上传文件名
           String filename = thumbnail.getOriginalFilename();
           String fileType = filename.substring(filename.lastIndexOf(".")+1);   //文件格式 
       		//组成文件实际路径 
        	String truePath=holePath+filename;
        	System.out.println("实际路径为："+truePath);
        	
        	thumbnail.transferTo(new File(truePath));
			String path = relativePath+filename;
			msg.setCode(0);
			msg.setContent(path);
			msg.setMessage("上传成功!");
		} catch (Exception e) {
			e.printStackTrace();
			msg.setCode(-1);
			msg.setMessage("上传失败!");
			return msg;
		}
		return msg;
	}
	
}
